package com.pvdnc.xdynamic.loader.module;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;

import com.pvdnc.xdynamic.common.XModule;
import com.pvdnc.xdynamic.loader.PackageParserUtils;
import com.pvdnc.xdynamic.loader.ResourceUtils;
import com.pvdnc.xdynamic.loader.mirror.PackageParser;

import java.io.File;

public class ModuleLoader {
    private static final String TAG=ModuleLoader.class.getSimpleName();

    private Context mContext;

    File mApkFile;

    public File getOriginApkFile(){
        return mApkFile;
    }

    private ModuleDir mDir;
    public ModuleLoader(Context context, File apkFile) throws Exception {
        mContext = context;
        mApkFile = apkFile;

        mModuleContext=new ModuleContext(context);
        parse();
    }

    private Resources mResources;
    private ModuleContext mModuleContext;

    private String mModuleName;
    private Object mPkg;

    public Context getModuleContext(){
        return mModuleContext.get();
    }

    public String getModuleName(){
        return mModuleName;
    }

    private ModuleClassLoader mLoader;
    private String mEntryClassName;

    private void parse() throws Exception {
        mPkg= PackageParserUtils.parsePackage(mApkFile);
        //生成ApplicationInfo
        ApplicationInfo appInfo= PackageParserUtils.generateApplicationInfo(mPkg);
        //获取apk内资源
        mResources= ResourceUtils.getResources(mContext,mApkFile);
        mModuleName= mResources.getString(appInfo.labelRes);
        Log.d(TAG,"module name:"+mModuleName);
        //目录结构
        mDir=new ModuleDir(mContext,mModuleName);
        //加载模块类
        mLoader=new ModuleClassLoader(mContext,this);

        mModuleContext.attach(appInfo,mDir,mLoader.getModuleClassLoader(),mResources);
        //获取模块入口
        Bundle metaDataBundle= PackageParser.Package.mAppMetaData.get(mPkg);
        Log.d(TAG,"meta data:\n\t"+metaDataBundle);
        mEntryClassName=metaDataBundle.getString("xdynamic_module");
        Log.d(TAG,"entry class:"+mEntryClassName);

    }

    public Class<? extends XModule> loadEntryClass() throws ClassNotFoundException {
        //加载模块类
        Class<?> entryClass= mLoader.loadClass(mEntryClassName);
        Log.d(TAG,"entry class:"+entryClass);
        return (Class<? extends XModule>) entryClass;
    }

    public ModuleDir getModuleDir(){
        return mDir;
    }
}
